import json
from config.log_config import AntLogger

class JsonPlaceholderReplacer:
    def __init__(self, json_data):
        # 将 JSON 字符串解析为 Python 字典
        self.json_data = json.loads(json_data) if isinstance(json_data, str) else json_data

    def replace_placeholder(self, placeholder, value):
        """递归地在 JSON 中替换占位符"""
        self._replace_recursive(self.json_data, placeholder, value)

    def _replace_recursive(self, data, placeholder, value):
        """递归地遍历和替换 JSON 数据中的占位符"""
        if isinstance(data, dict):
            for key, val in list(data.items()):
                if isinstance(val, (dict, list)):
                    self._replace_recursive(val, placeholder, value)
                elif val == placeholder:
                    # 如果值完全匹配占位符，将其替换为对象或列表
                    data[key] = value
        elif isinstance(data, list):
            for index, item in enumerate(data):
                if isinstance(item, (dict, list)):
                    self._replace_recursive(item, placeholder, value)
                elif item == placeholder:
                    # 如果列表中的项完全匹配占位符，将其替换为对象或列表
                    data[index] = value

    def get_modified_json(self):
        """返回替换后的 JSON 字符串"""
        return json.dumps(self.json_data, ensure_ascii=False, indent=4)

# 使用示例
if __name__ == "__main__":
    # JSON 文本示例
    json_data = '''
    {
        "name": "Sample",
        "data": "__STOCK_DATA__",
        "items": ["item1", "__STOCK_DATA__"],
        "details": {
            "info": "__STOCK_DATA__",
            "list": [{"key": "__STOCK_DATA__"}]
        }
    }
    '''

    # 要替换的值，可以是一个对象或列表
    stock_data = [
        {"symbol": "AAPL", "price": 150.23},
        {"symbol": "GOOGL", "price": 2784.34}
    ]

    replacer = JsonPlaceholderReplacer(json_data)
    replacer.replace_placeholder("__STOCK_DATA__", stock_data)
    AntLogger.info(replacer.get_modified_json())
